package org.thomias.exo6.swtmultithread;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.TableItem;

public class BarUpdater implements Runnable {

	private TableItem item;
	private ProgressBar pb;
	private Application app;
	private long startTime;
	private int nbr;
	private int i;
	protected long elapsed;

	public BarUpdater(Application application, int nbr) {
		this.startTime = System.currentTimeMillis();
		this.app = application;
		this.nbr = nbr;
	}

	@Override
	public void run() {
		app.getShell().getDisplay().asyncExec(new Runnable() {

			public void run() {
				app.editors[nbr] = new TableEditor(app.table);
				app.editors[nbr].grabHorizontal = true;
				app.editors[nbr].horizontalAlignment = SWT.LEFT;
				item = new TableItem(app.table, SWT.NONE);
				pb = new ProgressBar(app.table, SWT.HORIZONTAL | SWT.SMOOTH);
				pb.setMinimum(0);
				pb.setMaximum(100);
				app.editors[nbr].setEditor(pb, item, 3);
			}
		});
		double speed = Math.random();
		for (i = 0; i < 100; i++) {
			final long sleep = (long) (speed * Math.random() * 1000);
			try {
				Thread.sleep(sleep);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			app.getShell().getDisplay().asyncExec(new Runnable() {
				public void run() {
					elapsed = (System.currentTimeMillis() - startTime) / 100;
					int left = 100 - i;
					double speed2 = 1 / (double) sleep;
					int remaining = (int) (((double) elapsed / (double) i) * left) / 10;
					item.setText(new String[] { "thread" + nbr, "10B", "U", "",
							speed2 + "progress/s", elapsed / 10 + "s",
							remaining + "s" });
					if (pb.isDisposed()) {
						return;
					}
					pb.setSelection(pb.getSelection() + 1);
				}
			});
		}
		app.getShell().getDisplay().asyncExec(new Runnable() {
			public void run() {
				pb.dispose();
				item.dispose();
				app.editors[nbr].dispose();
				app.refresh();
			}
		});
	}
}
